<template>
  <el-container v-if="isPc()">
    <el-header class="nav-container">
      <div class="layout-header">
        <div class="logo">
          <img :src="logo" />
          <h1>{{ app.name }}</h1>
        </div>
        <div class="nav-items-container">
          <el-menu
            mode="horizontal"
            active-text-color="#2362FB"
            @select="navItemsClick"
            :default-active="appActivePath"
            ref="appMenu"
          >
            <template v-for="(item, index) in subapps">
              <el-menu-item
                :key="index"
                :index="item.path"
                v-if="index < topAppCount"
                style="height:60px;line-height: 60px;"
              >
                <svg-icon :icon-class="item.icon" />
                <span class="menu-title">{{ item.name }}</span>
              </el-menu-item>
            </template>
            <el-menu-item ref="moreAppMenu" index="more" style="height:60px;line-height: 60px;"> 
              <svg-icon icon-class="more" />
              <!-- <span class="menu-title">更多</span> -->
            </el-menu-item>
          </el-menu>
        </div>

        <el-badge is-dot type="primary" :value="12">
          <i class="el-icon-sort badge-icon" @click="uploadListShow=true;showUpload=false" />
        </el-badge>

        <el-badge :value="0" type="primary" :hidden="false">
          <i class="el-icon-message-solid badge-icon" />
        </el-badge>

        <el-dropdown trigger="click">
          <div class="user-container">
            <el-avatar icon="el-icon-user-solid"  :src="user.avatar" size="small" class="avatar">
            </el-avatar>
            <span class="user-name">{{ user.name }}</span>
            <i class="el-icon-caret-bottom mark" />
          </div>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="logout()" style="font-size: 12px"
              >退出登录</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
        <more-app
          ref="moreApp"
          v-if="moreAppShow"
          :subapps="subapps"
          @select="navItemsClick"
        ></more-app>
        
      </div>
    </el-header>
    <el-container>
      <el-aside
        class="sidebar"
        v-bind:class="{ 'sidebar-collapse': isCollapse }"
        v-if="menus.length > 1"
      >
        <el-scrollbar>
          <el-menu
            :default-active="value"
            @select="handleSelect"
            :collapse="isCollapse"
            :collapse-transition="false"
            active-text-color="rgb(24, 144, 255)"
            class="menu"
            :router="true"
          >
            <memu-item :menus="menus" :isCollapse="isCollapse" />
          </el-menu>
        </el-scrollbar>
        <slot name="bottom" />
        <div class="sidebar-powerby">
          <span>
            <img
              v-if="!isCollapse"
              class="sidebar-powerby-logo"
              :src="logo"
              width="20px"
            />
            <span v-if="!isCollapse" class="sidebar-powerby-title">
              version: {{ version }}
            </span>
          </span>
          <i
            class="el-icon-s-fold sidebar-toggle"
            v-if="!isCollapse"
            @click="actionMenu"
          ></i>
          <i
            class="el-icon-s-unfold sidebar-toggle"
            v-if="isCollapse"
            @click="actionMenu"
          ></i>
        </div>
      </el-aside>
      <el-main class="content">
        <div v-loading="loading">
          <div id="container"></div>
          <router-view v-if="!microAppsActive" />
        </div>
      </el-main>
    </el-container>
    <filebase-upload v-model="uploadListShow" :showUpload.sync="showUpload"></filebase-upload>
  </el-container>
  <el-container v-else>
    <el-container>
      <el-main class="content">
      <div id="container"></div>
      <router-view v-if="!microAppsActive" />
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import { registerMicroApps, start } from "@ice/stark";
import idaas from "@/apis/idaas";
import logoImg from "@/assets/logo.png";
import { on, off } from "@/utils/dom";
import MemuItem from "./item.vue";
import MoreApp from "./more.vue";
import FilebaseUpload from "@/components/FilebaseUpload";

export default {
  data() {
    return {
      version: "0.1.0",
      isCollapse: false,
      loading: false,
      microAppsActive: false,
      user: {
        name: "",
        avatar: "",
      },
      menus: [],
      title: "应用系统",
      logo: logoImg,
      app: {},
      fullname: {},
      curName: [],
      subapps: [],
      moreAppShow: false,
      appActivePath: "",
      topAppCount: 5,
      uploadListShow: false,
      showUpload: false,
    };
  },
  name: "Layout",
  components: {
    MemuItem,
    MoreApp,
    FilebaseUpload
  },
  computed: {
    value() {
      return this.$route.path;
    },
  },
  watch: {
  },
  async mounted() {
    this.userinfo();
    this.version = process.env.VUE_APP_VERSION;
    on(document, "click", this.handleDocumentClick);
    const rect = document.body.getBoundingClientRect();
    this.openMenu = rect.width - 1 > 992;
    await this.regApp();
    await this.initMenu();
  },
  beforeDestroy() {
    off(document, "click", this.handleDocumentClick);
  },
  methods: {
    async initMenu() {
      // let menus = await idaas.getMenus("");
      // this.menus = menus.data;
      // this.fetchMenuName(this.menus, "", []);
      // this.setPath(this.$route.path);

      this.appActive();
      let app = await idaas.getApp();
      this.app = app.data;
      let paths = this.$route.path.split("/");
      if (paths.length > 1) {
        this.navItemsClick2("/" + paths[1],this.$route.path,this.$route.query);
      }
    },
    appActive() {
      this.appActivePath = "/" + this.$route.path.split("/")[1];
    },
    async navItemsClick(path){
      this.navItemsClick2(path)
    },
    async navItemsClick2(path,fullpath,query) {
      this.appActivePath = path;
      if (path == "more") {
        this.moreAppShow = true;
        return;
      }
      this.moreAppShow = false;
      let id = "";
      let _this = this;
      this.subapps.forEach((element, index) => {
        if (index > _this.topAppCount - 1 && id == "") {
          this.appActivePath = "more";
        }
        if (element.path == path) {
          id = element.id;
          return false;
        }
      });
      if (id) {
        let menus = await idaas.getMenus(id);
        this.menus = menus.data;
      }
      if (!fullpath){
        fullpath=path
      }
      this.$router.push({path:fullpath,query:query});
    },

    async regApp() {
      const container = document.getElementById("container");
      let subapps = await idaas.getSubApps();
      this.subapps = subapps.data;
      let apps = new Array();
      subapps.data.map((item) => {
        if (item.path == process.env.VUE_APP_BASE) {
          return;
        }
        let path = item.path;
        if (process.env.VUE_APP_BASE != "/") {
          path = process.env.VUE_APP_BASE + item.path;
        }
        apps.push({
          name: item.id,
          activePath: path,
          title: item.name,
          sandbox: true,
          container,
          entry: item.entry,
        });
      });
      registerMicroApps(apps);
      start({
        onLoadingApp: () => {
          this.loading = true;
        },
        onFinishLoading: () => {
          this.loading = false;
        },
        onRouteChange: (_, pathname) => {
          // 处理微应用间跳转无法触发 Vue Router 响应
          console.log(pathname);
          this.setPath(pathname);
          //this.$router.push(pathname).catch(() => {});
        },
        onActiveApps: (activeApps) => {
          this.microAppsActive = (activeApps || []).length;
        },
      });
    },
    actionMenu() {
      this.isCollapse = !this.isCollapse;
    },
    handleSelect(key) {
      if (document.body.getBoundingClientRect().width - 1 < 992) {
        this.isCollapse = true;
      }
      console.log(key);
      this.setPath(key);
      //this.$router.push(key);
    },
    handleDocumentClick(e) {
      if (
        !this.$refs.moreAppMenu ||
        !this.$refs.moreApp ||
        this.$refs.moreAppMenu.$el.contains(e.target) ||
        this.$refs.moreApp.$el.contains(e.target)
      )
        return;
      this.moreAppShow = false;
      this.appActive();
    },
    setPath(pathname) {
      if (pathname.substr(pathname.length - 1, 1) != "/") {
        pathname += "/";
      }
      this.curName = this.fullname[pathname];
    },
    fetchMenuName(menus, path, names) {
      let _that = this;
      menus.forEach((menu) => {
        let npath = path + "/" + menu.path;
        let nnames = [...names];
        nnames.push(menu.meta.title);
        if (menu.path.substr(0, 1) == "/") {
          npath = path + menu.path;
        }
        if (menu.children.length == 0) {
          if (npath.substr(npath.length - 1, 1) != "/") {
            npath += "/";
          }
          _that.fullname[npath] = nnames;
        } else {
          _that.fetchMenuName(menu.children, npath, nnames);
        }
      });
    },
    logout() {
      this.$confirm("退出系统登录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.location.href = "/idaas/app/logout";
      });
    },
    userinfo() {
      idaas.userinfo().then((resp) => {
        this.user.name = resp.data.nickName;
        this.user.avatar = resp.data.avatar;
      });
    },
    isPc(){
        if(window.navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)) {
          return false; // 移动端
        }
        return true; // PC端
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  flex: 1;
  height: calc(100vh - 60px);
}
.menu {
  height: calc(100vh - 95px);
}
</style>